#!/bin/bash

#请根据自己情况修改下面的代码

magisk_path=/root/Magisk  #脚本创建的所有文件的保存目录

#获取最新magisk版本号
new_ver=$(
        wget -t2 -T3 -qO- "https://channel.topjohnwu.com/stable.json" | grep -o '"version": ".*"' | head -n 1 | cut -d'"' -f4 
    )
#获取最新note版本号
note_ver=$(
        wget -t2 -T3 -qO- "https://channel.topjohnwu.com/stable.json" | grep -o '"versionCode": ".*"' | head -n 1 | cut -d'"' -f4 
    )
#获取最新stub版本号
stub_ver=$(
        wget -t2 -T3 -qO- "https://channel.topjohnwu.com/stable.json" | grep -o '"versionCode": ".*"' | cut -d'"' -f4 | sed '1d'
    )
#设置json版本号
json_ver=$(
        wget -t2 -T3 -qO- "https://channel.topjohnwu.com/stable.json" | grep -o '"version": ".*"' | cut -d'"' -f4
    )
#本地下载目录
path=$magisk_path/stable/$new_ver
#如果文件夹不存在，创建文件夹
if [ ! -d "$magisk_path" ]; then 
    mkdir -p $magisk_path
else
    cd ~
fi
if [ ! -d "$magisk_path/stable" ]; then 
    mkdir -p $magisk_path/stable
else
    cd ~
fi
#如果文件不存在，创建文件
if [ ! -f "$magisk_path/ver.txt" ]; then
    cd $magisk_path
    echo "v00.0" > ver.txt
else
    cd ~
fi
#获取已有版本号
ver=$(
    cat $magisk_path/ver.txt
    )
#获取更新
if [ $new_ver == $ver ]
then
    echo "目前不需要更新"
else
    rm -rf $magisk_path/ver.txt
    mkdir $path
    wget https://raw.github.com/topjohnwu/magisk-files/$new_ver/app-release.apk -O $path/app-release.apk   
    wget https://raw.github.com/topjohnwu/magisk-files/$new_ver/stub-release.apk -O $path/stub-release.apk
    wget https://topjohnwu.github.io/Magisk/releases/$note_ver.md -O $path/$note_ver.md
#    cp $magisk_path/stable.json $magisk_path/$ver.json
#    rclone copy $magisk_path/$ver.json webdav:/magisk
    rm -rf $magisk_path/stable.json
    echo "{
  "\"magisk"\": {
    "\"version"\": "\"$json_ver"\",
    "\"versionCode"\": "\"$note_ver"\",
    "\"link"\": "\"https://pan.lm379.cn/d/magisk/stable/$new_ver/app-release.apk"\",
    "\"note"\": "\"https://pan.lm379.cn/d/magisk/stable/$new_ver/$note_ver.md"\"
  },
  "\"stub"\": {
    "\"versionCode"\": "\"$stub_ver"\",
    "\"link"\": "\"https://pan.lm379.cn/d/magisk/stable/$new_ver/stub-release.apk"\"
  }
}" > $magisk_path/stable.json
    rm -rf $magisk_path/ver.txt
    rm -rf $magisk_path/$ver
    cd  $magisk_path
    echo "$new_ver" > ver.txt  #写入版本信息
    rclone copy $path webdav:/magisk/stable/$new_ver/ --transfers=1   #上传文件并设定最大并行任务数为1，如不使用rclone请将这三行代码注释
    rclone delete webdav:/magisk/stable.json
    rclone copy $magisk_path/stable.json webdav:/magisk
    echo "更新完成"
fi
